import { RoleManager } from "./role.manager";

// 管理器定义
export class SpawnManager {

  static run() {
    for (const spawnName in Game.spawns) {
      const spawn = Game.spawns[spawnName];
      const room = spawn.room;
      if (spawn.spawning) continue;

      // 计算可用能量 (取可用容量和当前能量的最小值)
      const energyCapacity = room.energyCapacityAvailable;
      const currentEnergy = room.energyAvailable;
      const roomEnergy = Math.min(energyCapacity, currentEnergy);

      const role = this.getOptimalCreepRole(room, roomEnergy);
      if (!role) {
        if (Game.time % 20 === 0) {
          console.log(`🔋 ${spawn.name} 能量不足或无需生成creep`);
        }

        continue;
      }

      this.spawnCreep(spawn, role);
    }
  }

  private static spawnCreep(spawn: StructureSpawn, role: RoleType) {
    const body = RoleManager.getBodyForRole(role);
    if (!body || body.length === 0) {
      console.log(`❌ ${spawn.name} 无法获取 ${role} 的身体配置`);
      return;
    }

    const memory: CreepMemory = {
      role,
      working: false,
      room: spawn.room.name
    }

    const name = `${role.slice(0, 3).toUpperCase()}_${Game.time}`;
    const result = spawn.spawnCreep(body, name, { memory });

    if (result === OK) {
      console.log(`🚀 ${spawn.name} 生成 ${role} [${body.join('|')}]`);
    } else if (result !== ERR_NOT_ENOUGH_ENERGY) {
      console.log(`❌ ${spawn.name} 生成 ${role} 失败: ${getErrorString(result)}`);
    }
  }

  private static getOptimalCreepRole(room: Room, roomEnergy: number): RoleType | null {
    // 1. 获取房间中存在的 creep (基于实际位置而非内存属性)
    const roomCreeps = this.getRoomCreeps(room);

    // 2. 获取所有角色类型并初始化计数
    const allRoles = RoleManager.getAllRoleTypes();
    const roleCounts = this.initRoleCounts(allRoles);

    // 3. 统计各角色数量
    this.countsByRole(roomCreeps, roleCounts);

    // 4. 添加调试输出
    this.logRoleCounts(roleCounts, room.name);

    // 5. 根据游戏策略决定下一个角色
    return this.determineNextRole(roleCounts, room, roomEnergy);
  }

  // 获取房间中的 creep
  private static getRoomCreeps(room: Room): Creep[] {
    return _.filter(Object.values(Game.creeps), creep => creep.pos.roomName === room.name);
  }

  // 初始化角色计数
  private static initRoleCounts(roles: RoleType[]): Record<RoleType, number> {
    return roles.reduce((acc, role) => {
      acc[role] = 0;
      return acc;
    }, {} as Record<RoleType, number>);
  }

  // 统计角色数量
  private static countsByRole(creeps: Creep[], counts: Record<RoleType, number>) {
    creeps.forEach(creep => {
      const role = creep.memory.role;
      if (role && counts[role] !== undefined) {
        counts[role]++;
      }
    });
  }

  // 决定下一个角色
  private static determineNextRole(counts: Record<RoleType, number>, room: Room, energy: number): RoleType | null {
    // 策略1: 保持最少的基础采集者
    if (counts.harvester < 2) {
      return 'harvester';
    }

    // 策略2: 确保有资源运输者
    if (counts.transporter < 2 && counts.harvester >= 2) {
      return 'transporter';
    }

    // 策略3: 优先升级控制中心
    if (room.controller?.level && room.controller.level < 4 && counts.upgrader < 3) {
      return 'upgrader';
    }

    // 策略5: 检查建筑进度
    const constructionSites = room.find(FIND_CONSTRUCTION_SITES).length;
    if (constructionSites > 0 && counts.builder < 1) {
      return 'builder';
    }

    return null;
  }

  /**
     * 日志记录角色数量 (每10个tick记录一次)
     */
  private static logRoleCounts(counts: Record<RoleType, number>, roomName: string): void {
    if (Game.time % 10 === 0) {
      console.log(`📊 [${roomName}] 角色统计:`);
      Object.entries(counts).forEach(([role, count]) => {
        console.log(`➤ ${role}: ${count}`);
      });
    }
  }
}

// ✅ 错误代码转可读字符串
function getErrorString(code: number): string {
  const errorMap: Record<number, string> = {
    [ERR_NAME_EXISTS]: "名称重复",
    [ERR_BUSY]: "生成器忙碌",
    [ERR_NOT_OWNER]: "无权操作",
    [ERR_INVALID_ARGS]: "参数无效",
    [ERR_RCL_NOT_ENOUGH]: "房间等级不足"
  };
  return errorMap[code] || `错误代码 ${code}`;
}

